<?php
/**
 * Created by PhpStorm.
 * User: function
 * Date: 2018-04-12
 * Time: 9:09
 */

namespace app\common\logic;

use app\common\logic\Logic;
use app\common\model\Mall;
use app\common\model\OrderUuid;
use app\common\model\Purchaser;
use app\common\logic\MallLogic;
use app\common\model\Order;
use app\common\model\Goods;
use app\common\model\UnifiedOrder;
use app\common\model\Pay;
use app\common\model\Member;
use app\common\Logic\PayLogic;
use think\Log;

class OrderLogic extends Logic
{
    protected $modelClass = 'app\common\model\Order';
    protected $column = 'id,mid,mall_id,goods_id,amout,price,total,create_time,status,user_id,seller';
    
    protected $addRule = [
        'mid|订单类型' => 'require',
        'buyer|用户id' => 'require',
        'amount|订单总价' => 'require',
        'seller|商家信息' => 'require',
        'fee|订单运费总额' => 'require',
        'trade_no|公共单号' => 'require',
        'buyer_name|收货人' => 'require',
        'buyer_address|收货地址' => 'require',
        'buyer_postcode|邮编' => 'require',
        'buyer_phone|联系方式' => 'require'
    ];
    
    public function checkUnifiedOrderPayStatus($out_trade_no){
        $pay = Pay::get(['out_trade_no'=>$out_trade_no]);
        return $pay;
    }
    
   
    
    public static function createUuid()
    {
        $uuid = new OrderUuid();
        $uuid->create_time = time();
        $uuid->save();
        return $uuid->id;
    }
    
    /**
     * 一个一个店来加，单个的也是这样
     */
    /**
     * @param $company
     * @param $userId
     * @param $out_trade_no 多订单共用单号，用于第三方支付
     * @param int $mid 订单类型
     * @return bool
     * @throws \think\exception\DbException
     */
    public function addOrder($company, $address, $userId, $out_trade_no, $mid = 1)
    {
        //companlist
        $post = [];
        $post['amount'] = (int)$company['amountTotal'] + (int)$company['feeTotal'];
        $post['user_id'] = $userId;
        $member = Member::get($userId);
        $post['user_nickname'] = $member['nickname'];
        
        $post['seller'] = $company['seller_id'];
        $post['seller_name'] = $company['company'];
        $post['mid'] = $mid;//默认是1商品,及时有团购的订单，也不好说。因为有购物车会把订单统一符合在一起的
//        $post['buyer'] = $userId;
        $post['fee'] = $company['feeTotal'];//听说这里的物流费用，要按照商品的价格来区分，比如100块邮费，两个商品，一个总价格是60一个是40，那邮费也要切割。。不然最后有问题退款的话商家吃亏
        $post['trade_no'] = $this->createUuid();//递增订单号
        
        $post['buyer_name'] = $address['link'];
        $post['buyer_address'] = $address['province'].$address['city'].$address['area'].$address['detail'];
        $post['buyer_postcode'] = $address['postalCode'];
        $post['buyer_phone'] = $address['tel'];
        $this->validate($post, $this->addRule);
        
        $order = new Order();
        $order->allowField(true)->save($post);
        if ($order->id) {
            
            //公共订单号的对应关系了解一下
            $unified = new UnifiedOrder();
            $unified->allowField(true)->save(['order_id' => $order->id, 'out_trade_no' => $out_trade_no]);
            
            //拼命填购买表信息
            $rt = true;
            foreach ($company['malls'] as $mall) {
                $rt2 = $this->addPurchaser($order->id, $userId, $mall);
                if (!$rt2) $rt = false;
            }
        }
        return $order->id && $rt ? $order->id : false;//能走到这里肯定赢了
    }
    
    /**
     * @param $orderId
     * @param $userId
     * @param $mall
     * @return bool|mixed
     * @throws \think\exception\DbException
     */
    public function addPurchaser($orderId, $userId, $mall)
    {
        $rt = true;
        $mallLogic = new MallLogic();
        
        $post = [];
        $post['mall_id'] = $mall['mallid'];
        $post['user_id'] = $userId;
        $post['order_id'] = $orderId;
        $post['goods_id'] = $mall['goodsid'];
        $post['number'] = $mall['number'];
        $post['price'] = $mall['price'];
        $post['title'] = $mall['title'];
        $post['thumb'] = $mall['thumb'];
        
        if ($post['number'] > $mallLogic->getStock($post['mall_id'])) {
            $order = Order::get($orderId);
            $order->delete();
            abort(500, $post['mall_id'] . '库存不足，下单失败');
        }
        
        $purchaser = new Purchaser();
        $purchaser->allowField(true)->save($post);
       
        
        return $rt ? $purchaser->id : false;
        
    }
    
    
    /**
     * @desc 表单回调
     * @param $out_trade_no
     * @param $channel
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @type 1为支付，给退款啥的留好空间.
     */
    public function callOrder($out_trade_no, $channel, $type = 1)
    {
        $mallLogic = new MallLogic();
        $orderIds = UnifiedOrder::where('out_trade_no', $out_trade_no)->field('order_id')->select();
        if (count($orderIds) < 1) {
            Log::error('该大订单下没有子订单' . $out_trade_no);
        }
        
        foreach ($orderIds as $orderId) {
            
            $order = Order::where('id', $orderId['order_id'])->field('id,amount,status')->find();
            $this->changeOrderStatus($order->id,1);
            
            $purchasers = Purchaser::where('order_id',$order->id)->field('mall_id,number,goods_id,user_id')->select();
            foreach($purchasers as $purchaser) {
                $mallLogic->changeStock($purchaser['mall_id'], $minux = true, $purchaser['number']);//支付成功，减库存
                $mall = Mall::get($purchaser['mall_id']);
                $mall->sales += $purchaser['number'];
                $mall->isUpdate()->save();
                
                $goods = Goods::get($purchaser['goods_id']);
                $goods->sales += $purchaser['number'];
                $goods->isUpdate()->save();
            }
           
        }
        
        $pay = Pay::get(['out_trade_no' => $out_trade_no]);
        $pay->status = 1;
        $pay->isUpdate()->save();
        
        Log::info($out_trade_no . '回调处理成功');
        
    }
    
    //0=>'待付款',1=>'待发货',2=>'待收货',3=>'待评价',4=>'退款/售后',-1=>'为订单失败'
    public function changeOrderStatus($orderId, $status)
    {
        
        $order = Order::get($orderId);
        if (!$order) {
            abort(500, '订单不存在');
        }
        switch ($status) {
            case 0:
                if (!$order) {
                    Log::error($orderId['order_id'] . '子订单获取失败');
                }
                if ($order->status != 0) {
                    Log::error($orderId['order_id'] . '已有部分子订单支付，请进入订单中心分开支付');
                }
                $order->status = 0;
                $order->save();
                break;
            case 1:
                //检查支付信息
                $pay = Pay::get(['out_trade_no' => $order->unifiedOrder->out_trade_no]);
                if ($pay->status != 1) {
                    return false;
                }
                $order->status = 1;
                //修改物流状态为待发货
                $order->send_status =1;
                $order->save();
                
                
                break;
            case 2:
                if (!$order->send_type || !$order->send_no) {
                    return callerror('物流信息未填写完全，无法发货');
                }
                $order->status = 2;
                $order->save();
                break;
            case 4:
    
                if($order->status !=2){
                    error('订单状态不符合，只有待收货的订单才可以收货');
                }
                $order->status = 4 ;//确认收货
                $order->send_status = 4;//配送状态,0为等待支付,1为待发货，2已发货,3正在配送，4已配送
                $order->isUpdate()->save();
                
                try {
                    $company = Member::get($order->seller);
                    $rt = $company->changeAmount($order->amount,1,1,'订单'.$order->id.'确认收货，系统结算到商家账户',$order->id);
                    if(!$rt){
                        return false;
                    }
                } catch (Exception $e) {
                    log::info('订单' . $order->id . '在给商家分润时出现问题');
                    return false;
                }
                
                break;
            case 5:
                $order->status = 5;
                $order->save();
                break;
            case 6:
                $order->status = 6;
                $order->save();
                break;
            case -1:
                $order->status = -1;
                $order->save();
                break;
            default:
                return false;
                break;
        }
        
        return true;
        
        
    }
    
    
    
    
    public function getUnifiedOrder($orderId)
    {
        $unifiedOrder = UnifiedOrder::where('order_id', $orderId)->order('id desc')->find();
        return $unifiedOrder;
    }
    
    public function getPurchaser($orderId)
    {
        $purchasers = Purchaser::where('order_id', $orderId)->select();
        $mallLogic = new MallLogic();
        foreach ($purchasers as $purchaser) {
            $purchaser->mallSpec = $mallLogic->getMallSpec($purchaser->mall_id);
        }
        return $purchasers;
    }
    
    
}